package org.tloss.web.editor.enity.service;

import java.util.List;
import java.util.Map;

import org.tloss.web.editor.Utils;
import org.tloss.web.editor.database.editors.jdbc.Column;
import org.tloss.web.editor.database.editors.jdbc.Mapping;
import org.tloss.web.editor.database.editors.jdbc.Table;
import org.tloss.web.editor.model.Database;

public class GenerateEntityUtils {

	public static void generateDefaultMapping(Map<Integer, String> typeMapping) {
		typeMapping.put(1, "java.lang.String");
		typeMapping.put(12, "java.lang.String");
		typeMapping.put(-4, "byte[]");
		typeMapping.put(93, "java.util.Date");
		typeMapping.put(92, "java.util.Date");
		typeMapping.put(4, "java.lang.Integer");
		typeMapping.put(-7, "java.lang.Integer");
		typeMapping.put(7, "java.lang.Float");
		typeMapping.put(-1, "java.lang.String");
		typeMapping.put(4, "java.lang.Integer");
		typeMapping.put(-5, "java.lang.Integer");
		typeMapping.put(5, "java.lang.Integer");
		typeMapping.put(-6, "java.lang.Integer");
		typeMapping.put(8, "java.lang.Double");

	}

	public static boolean supportedByURL(Database database, String protocol) {
		// "jdbc:derby:MyDbTest;create=true"
		String url = database.getJdbcURL();
		if (url != null && protocol != null) {
			String[] urls = url.split(":");
			return urls.length >= 2 && protocol.equals(urls[1]);
		}
		return false;
	}

	public static Table generateByMapping(Table table,
			Map<Integer, String> typeMapping) {

		List<Column> columns = table.getColumns();
		if (columns != null) {
			Column column;
			for (int i = 0; i < columns.size(); i++) {
				column = columns.get(i);
				Utils.logInfo("dataType : " + column.getDataType()
						+ " typeName:" + column.getTypeName());
				if (typeMapping.containsKey(column.getDataType())) {
					Mapping mapping = new Mapping();
					mapping.setName(column.getColumnName());
					mapping.setType(typeMapping.get(column.getDataType()));
					mapping.setIsCollection(false);
					if (mapping.getType().endsWith("[]")) {
						mapping.setIsArray(true);
					}
					column.setMapping(mapping);

				} else {
					Utils.logInfo("not found : " + column.getDataType()
							+ " typeName:" + column.getTypeName());

				}
			}
		}
		return table;
	}
}
